import Vue from 'vue'
import routeUtil from '../../core/route-interceptor'

import { APP_LANGUAGE, APP_THEME, MENU_COLLAPSE, SIDEBAR_THEME } from '../mutation-types'
import { loadLanguageAsync } from '../../locales'
import { addClass, removeClass, hasClass } from '@/utils/dom'
import { themeKey, languageKey, debug, sidebarThemeKey } from '../../env'
import { routes } from '@/router'

const state = {
  lang: 'zh-CN',
  theme: 'skin-default',
  sidebarTheme: 'theme-1',
  menuCollapse: false
}

const getters = {
  menus: (state, getters, rootState, rootGetters) => routeUtil.filter(routes, rootGetters['permissions'], debug || rootGetters['isSuper']),
  menuCollapse: state => state.menuCollapse
}

const mutations = {
  [APP_LANGUAGE] (state, lang) {
    Vue.ls.set(languageKey, lang)
    state.lang = lang
  },
  [SIDEBAR_THEME] (state, sidebarTheme) {
    Vue.ls.set(sidebarThemeKey, sidebarTheme)
    state.sidebarTheme = sidebarTheme
  },
  [APP_THEME] (state, theme) {
    Vue.ls.set(themeKey, theme)
    state.theme = theme
  },
  [MENU_COLLAPSE] (state, collapse) {
    state.menuCollapse = collapse
  }
}

const actions = {
  setLang ({ commit }, lang) {
    const promise = new Promise((resolve) => {
      loadLanguageAsync(lang).then(loadedLang => {
        commit(APP_LANGUAGE, loadedLang)
        resolve(loadedLang)
      })
    })

    return promise
  },

  setSidebarTheme ({ commit }, sidebarTheme) {
    commit(SIDEBAR_THEME, sidebarTheme)
  },

  setCollapse ({ commit }, collapse) {
    commit(MENU_COLLAPSE, collapse)
  },

  setTheme ({ commit }, theme) {
    const previousTheme = state.theme
    const dom = document.body
    if (hasClass(dom, theme)) {
      return
    }
    removeClass(dom, previousTheme)
    addClass(dom, theme)
    commit(APP_THEME, theme)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
